package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"mouth-project/model/mysql"
	"mouth-project/model/redis"
	"mouth-project/request"
	"net/http"
)

//订单创建

func OrderCreate(c *gin.Context) {
	var orderCreate request.OrderCreateReq
	if err := c.ShouldBindJSON(&orderCreate); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg":  "服务器内部错误",
			"code": 500,
			"err":  err.Error(),
		})
		return
	}

	data := mysql.Order{
		UserId:   orderCreate.UserId,
		GoodsId:  orderCreate.GoodsId,
		OrderSn:  uuid.NewString(),
		SumPrice: orderCreate.SumPrice,
		BuyNum:   orderCreate.BuyNum,
		Payment:  orderCreate.Payment,
	}
	err := data.Create()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg":  "订单创建失败",
			"code": 400,
			"err":  err.Error(),
		})
		return
	}
	redis.SyncOrder(orderCreate.UserId)
	c.JSON(http.StatusOK, gin.H{
		"msg":  "订单创建成功",
		"code": 200,
		"data": data,
	})
}

//订单详情

func OrderDetails(c *gin.Context) {
	var orderDetails request.GoodsInfoReq1
	if err := c.ShouldBindJSON(&orderDetails); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg":  "服务器内部错误",
			"code": 500,
			"err":  err.Error(),
		})
		return
	}
	redis.SyncOrderSearch(orderDetails.Id)
	data := mysql.Order{
		Model: gorm.Model{ID: uint(orderDetails.Id)},
	}
	err := data.Details()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg":  "订单查询失败",
			"code": 400,
			"err":  err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":  "订单查询成功",
		"code": 200,
		"data": data.OrderSn,
	})
}
